import { Sku } from '@/types/goods'
import useStore from '@/store'
import { CartItem } from '@/types/cart.d'
import { ApiRes } from '@/types/data'
import request from '@/utils/request'
import { defineStore } from 'pinia'
export default defineStore({
  id: 'cart',
  persist: {
    key: 'rabbit-cart-97'
  },
  state: () => ({
    list: [] as CartItem[]
  }),
  actions: {
    async addCart(data: CartItem) {
      if (this.isLogin) {
        const { skuId, count } = data
        await request.post('/member/cart', {
          skuId,
          count
        })
        // 重新获取购物车数据
        this.getCartList()
      } else {
        console.log('本地添加')
        // 1.判断购物车列表中是否有该商品数据
        const goods = this.list.find((item) => item.skuId === data.skuId)
        if (goods) {
          // 2.如果商品存在，直接把数量加起来
          goods.count += data.count
        } else {
          // 3.如果商品不存在，直接添加该商品
          this.list.unshift(data)
        }
      }
    },
    // 获取购物车列表
    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
        // console.log(res)
        this.list = res.data.result
      } else {
        this.list.forEach(async (cartItem) => {
          const { skuId } = cartItem
          // 根据skuId获取最新商品信息
          const res = await request.get<ApiRes<CartItem>>(
            `/goods/stock/${skuId}`
          )
          // 保存最新商品信息
          const lastCartInfo = res.data.result
          // 更新商品现价
          cartItem.nowPrice = lastCartInfo.nowPrice
          // 更新商品库存
          cartItem.stock = lastCartInfo.stock
          // 更新商品是否有效
          cartItem.isEffective = lastCartInfo.isEffective
        })
      }
    },
    // 删除购物车商品
    async deleteCart(skuIds: string[]) {
      if (this.isLogin) {
        await request.delete('/member/cart', {
          data: { ids: skuIds }
        })
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        this.list = this.list.filter((item) => !skuIds.includes(item.skuId))
      }
    },
    // 修改购物车商品
    async updateCart(
      skuId: string,
      data: { selected?: boolean; count?: number }
    ) {
      if (this.isLogin) {
        await request.put(`/member/cart/${skuId}`, data)
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        const sku = this.effectiveList.find((item) => item.skuId === skuId)
        if (data.selected !== undefined) sku!.selected = data.selected
        if (data.count !== undefined) sku!.count = data.count
      }
    },
    // 修改全选或者全不选
    async updateCartSelected(selected: boolean) {
      console.log(selected)
      if (this.isLogin) {
        await request.put('/member/cart/selected', {
          selected
        })
        this.getCartList()
      } else {
        this.list.forEach((item) => (item.selected = selected))
      }
    },
    // 清空购物车
    clearCart() {
      this.list = []
    },
    // 修改规格
    async updateCartSku(oldSkuId: string, sku: Sku) {
      if (this.isLogin) {
        const oldGoods = this.list.find((item) => item.skuId === oldSkuId)
        await request.delete('/member/cart', {
          data: {
            ids: [oldGoods?.skuId]
          }
        })
        await request.post('member/cart', {
          skuId: sku.id,
          count: oldGoods!.count
        })
        this.getCartList()
      } else {
        //删除原来的商品
        const oldSku = this.effectiveList.find(
          (item) => item.skuId === oldSkuId
        )!
        this.deleteCart([oldSkuId])
        // 2.添加新的商品
        this.addCart({
          ...oldSku,
          skuId: sku.id,
          nowPrice: sku.price,
          price: sku.price,
          stock: sku.inventory,
          attrsText: sku.specs
            .map((item) => item.name + ':' + item.valueName)
            .join(' ')
        })
      }
    },
    // 合并购物车
    async mergeLocalCart() {
      const data = this.list.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count
      }))
      await request.post('/member/cart/merge', data)
      // 合并成功，重新获取购物车列表
      this.getCartList()
    }
  },
  getters: {
    // 计算有效商品列表 isEffective = true
    effectiveList(): CartItem[] {
      return this.list.filter((item) => item.stock > 0 && item.isEffective)
    },
    // 有效商品总数量 把effectiveList中的每一项count相加
    effectiveListCount(): number {
      return this.effectiveList.reduce((sum, item) => sum + item.count, 0)
    },
    // 总价
    effectiveListPrice(): string {
      return this.effectiveList
        .reduce((sum, item) => sum + item.count * +item.nowPrice, 0)
        .toFixed(2)
    },
    // 是否全选
    isAllSelected(): boolean {
      return (
        this.effectiveList.length !== 0 &&
        this.effectiveList.every((item) => item.selected)
      )
    },
    // 已选择的列表
    selectedList(): CartItem[] {
      return this.effectiveList.filter((item) => item.selected)
    },
    // 已选择的商品总数
    selectedListCounts(): number {
      return this.selectedList.reduce((sum, item) => sum + item.count, 0)
    },
    // 已选择的商品总价
    selectedListPrice(): string {
      return this.selectedList
        .reduce((sum, item) => sum + item.count * +item.nowPrice, 0)
        .toFixed(2)
    },
    // 登录状态
    isLogin(): boolean {
      const { user } = useStore()
      return !!user.profile.token
    }
  }
})
